#pragma once

#include "IWebsocketClient.h"
#include <mutex>
#include <pthread.h>

class WWebsocketClient: public IWebsocketClient
{
public:
    WWebsocketClient(mg_mgr *websocketMgr = nullptr);
    virtual ~WWebsocketClient();
    virtual bool connect(string url);
    virtual bool disconnect();
    virtual bool sendMsg(const string &msg);
    virtual void setListener(IWebsocketClientCb *listener);
    virtual bool run();
    virtual bool isConnected();
    virtual void setAutoReconnect(bool flag);

private:
    struct mg_mgr *_websocketMgr = nullptr;
    struct mg_connection *_websocketConnection = nullptr;
    int _reConnectCount = 0;
    bool _startReConnectTimerFlag = false;
    struct mg_timer _reConnectTimer; // 一个mg_timer代表一个定时事件，若需要多个定时器，则需要多个mg_timer
    bool _connectFlag = false;
    bool _selfMgrFlag = false;
    bool _workFlag = false;
    bool _autoReconnectFlag = false;

    void innerDisconnect();
    void onReceiveMsg(struct mg_connection *connection, int dataType, void *data);
    void reConnect();
    string getIpFromDNS(const string &dnsStr, bool isIpv6First = false);

    static void receiveMsg(struct mg_connection *connection, int dataType, void *data, void *cbData);
    static void reconnectTimerEvent(void *arg);
};
